package arrays_;

import java.util.Arrays;
import java.util.Comparator;

/**
 * @author DCSGO
 * @version 1.0
 * 自定义Book类，里面包含name和price，按price排序。
 * 要求使用两种方式排序，对对象的某个属性排序
 */
public class ArrayExercise {
    public static void main(String[] args) {
        Book book1 = new Book("C++", 20);
        Book book2 = new Book("Java", 15);
        Book book3 = new Book("Go", 30);
        Book book4 = new Book("红楼梦", 40);
        Book book5 = new Book("活着", 25);

        Book[] books = {book1, book2, book3, book4, book5};
        System.out.println(Arrays.toString(books));
        //[C++ 20, Java 15, Go 30, 红楼梦 40, 活着 25]

        System.out.println("after sort:");

        Arrays.sort(books, new Comparator<Book>() {//价格升序
            @Override
            public int compare(Book o1, Book o2) {
                return o1.price-o2.price;
            }
        });
        System.out.println(Arrays.toString(books));
        //[Java 15, C++ 20, 活着 25, Go 30, 红楼梦 40]

        Arrays.sort(books, new Comparator<Book>() {//价格降序
            @Override
            public int compare(Book o1, Book o2) {
                return o2.price-o1.price;
            }
        });
        System.out.println(Arrays.toString(books));
        //[红楼梦 40, Go 30, 活着 25, C++ 20, Java 15]

        Arrays.sort(books, new Comparator<Book>() {//书名升序
            @Override
            public int compare(Book o1, Book o2) {
                return o1.name.compareTo(o2.name);
            }
        });
        System.out.println(Arrays.toString(books));
        //[C++ 20, Go 30, Java 15, 活着 25, 红楼梦 40]

        Arrays.sort(books, new Comparator<Book>() {//书名降序
            @Override
            public int compare(Book o1, Book o2) {
                return o2.name.compareTo(o1.name);
            }
        });
        System.out.println(Arrays.toString(books));
        //[红楼梦 40, 活着 25, Java 15, Go 30, C++ 20]
    }
}

class Book {
    String name;
    Integer price;

    Book() {
        name = null;
        price = 0;
    }

    @Override
    public String toString() {
        return name + " " + price;
    }

    public Book(String name, Integer price) {
        this.name = name;
        this.price = price;
    }
}
